package com.iris.live.services.common;

import com.iris.live.services.data.models.*;
import com.iris.live.services.data.repositories.*;
import com.iris.live.services.models.PageData;
import com.iris.live.services.models.ResultData;
import com.iris.live.services.services.ApprovalService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by DF on 2/23/2017
 */
@Component
@Transactional
public class ApprovalUtils {
    public static final int ORDER = 1;  //订单
    public static final int INTENTION_ORDER = 2;    //意向订单
    public static final int CONTRACT = 3;   //合同
    public static final int ORDER_CANCEL = 4;  //订单退订
    public static final int INTENTION_ORDER_CANCEL = 5;    //意向订单退订
    public static final int ORDER_MODIFY = 6;   //订单修改
    public static final int INTENTION_ORDER_MODIFY = 7; //意向订单修改
    public static final int TRANSFER_IN = 8;    //调车调入
    public static final int TRANSFER_OUT = 9;   //调车调出
    public static final int CONTRACT_MODIFY = 10;  //合同修改
    public static final int CONTRACT_CANCEL = 11; //合同退订
    public static final int INVOICE_MODIFY = 12;  //换票
    public static final int INVOICE_CANCEL = 13;    //退票
    public static final String STEP = "step";
    public static final String AGREE = "1";
    public static final String DISAGREE = "2";
    public static final String GROUP_PERMIT = "LSH";
    private static Logger logger = LoggerFactory.getLogger(ApprovalUtils.class);
    private static Lsh经销商表Repository dealerRepo;
    private static 用户Repository userRepo;
    private static 报价单表Repository qutdSheetRepo;
    private static Lsh车型Repository carRep;
    private static Lsh库存表Repository lsh库存表Repository;
    private static ApprovalService approvalService;
    private static Itask基础设置Repository itskSetRepo;

    /**
     * 根据权限和本单GP4.5调整审批流
     *
     * @param list 根据设置生成的原始审批流
     * @return 调整后的审批流
     */
    public static ResultData adjustApprovalFlowRco(List<PushApprovalWorkFlowModel> list) {
        //获取流程共性属性
        String permit = list.get(0).getPermit();
        String quotedPriceNumber = list.get(0).getQuotedPriceCodeOrVin();
        Integer qNum = Integer.parseInt(quotedPriceNumber);
        Integer type = list.get(0).getType();
        if (isContractType(type)) { // 合同，合同修改，换票流程，需要调整
            if (logger.isDebugEnabled()) logger.debug("list={}", JsonObjectUtils.writeAsJson(list));
            // 获取该流程对应的权限
            报价单表Model qMo = qutdSheetRepo.findOne(qNum);
            Lsh车型Model carMo = carRep.findOne(qMo.get车型编号());
            String carModelStr =carMo.get车型();
            String carDetailStr = carMo.get车型详细();
            String carStr = carMo.get品牌() + "__" + carMo.get级别() + "__" +carModelStr + "__" + carDetailStr;//carMo.get品牌() + "__" + carMo.get级别() + "__" + carMo.get车型();
            Integer needPriCount = list.size() - 1;
            List<Itask基础设置ModelPK> itaskPkList = new ArrayList<>(needPriCount); // 按审批人级数取权限
            for (int i = 0; i < needPriCount; i++) {
                Itask基础设置ModelPK pk = new Itask基础设置ModelPK();
                pk.set许可(permit);
                pk.set设置项目(STEP + (i + 1) + "__" + carStr);
                itaskPkList.add(pk);
            }
            List<Itask基础设置Model> itaskModelList = itskSetRepo.findAll(itaskPkList);
            Integer priCount = 0; // 有效的权限数量
            for (Itask基础设置Model mo : itaskModelList) {
                if (mo != null) {
                    priCount++;
                }
            }
            if (priCount == 0) {
                logger.warn("找不到ITask基础设置数据。itaskPkList={}", JsonObjectUtils.writeAsJson(itaskPkList));
                return new ResultData("false", "该车型暂未设置商务审批政策,禁止提交审核", null);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("ITask基础设置数据。itaskModelList={}", JsonObjectUtils.writeAsJson(itaskModelList));
            }
            if (needPriCount > priCount) { // 如果审批人很多，但权限设置数量比较少
                return new ResultData("false", "该车型对应商务政策不完整,禁止提交审核");
            }
            // 获取本单gp4.5
            BigDecimal gp4d5 = getGP4d5(qNum);
            if (logger.isDebugEnabled()){
                logger.debug("currentSnp=" + gp4d5);
            }
            // 比较当前snp与权限，必审批条目，修改审批流水
            List<PushApprovalWorkFlowModel> reList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
//                if (logger.isDebugEnabled()) {
//                    logger.debug("Double.parseDouble(itaskModelList.get(i).get值())=" + itaskModelList.get(i).get值());
//                }
                if (i == 0) { // 1级是销售顾问，只有销售顾问进入审批流
                    reList.add(list.get(0));
                } else {
                    BigDecimal pri;
                    try {
                        pri = new BigDecimal(itaskModelList.get(i - 1).get值());
                    } catch (Exception e) {
                        logger.error("系统中权限值非法", e);
                        return new ResultData("false", "系统中权限值非法", null);
                    }
                    // 是否需要二级审批人处理，由一级审批人的权限，及当前gp4.5决定，所以是和前一级审批人的权限比较
                    if (gp4d5.compareTo(pri) < 0) { // 当前gp4.5小于权限值，添加进审批流水
                        reList.add(list.get(i));
                    } // 否则不参与审批
                }
            }
            list = reList;
        }
        logger.warn("return list=" + JsonObjectUtils.writeAsJson(list));
        return new ResultData("true", null, new PageData(list, list.size()));
    }

    // 获取本单SNP的方法
//    public static String getSnp(Integer quotedPriceNumber) {
//        ApprovalService.getSNPRequest getSNPRequest = new ApprovalService.getSNPRequest();
//        getSNPRequest.quotedPriceCode = quotedPriceNumber + "";
//
//        List snpList = approvalService.getSNP(getSNPRequest);
//        return (String) ((Map) snpList.get(0)).get("result");
//    }

    public static BigDecimal getGP4d5(Integer qNum) {
        return approvalService.getGp4d5(qNum);
    }

    public static Boolean isContractType(Integer type) {
        return type == CONTRACT || type == CONTRACT_MODIFY || type == INVOICE_MODIFY;
    }

    public static Boolean isFinancialDepositType(Integer type) {
        return type == ORDER || type == INTENTION_ORDER || type == ORDER_MODIFY || type == INTENTION_ORDER_MODIFY || type == ORDER_CANCEL || type ==INTENTION_ORDER_CANCEL;
    }

    public static Boolean isThirdBoutiqueType(Integer type) {
        return type == CONTRACT_MODIFY || type == INVOICE_MODIFY || type == INVOICE_CANCEL;
    }

    @Autowired
    public void setLsh经销商表Repository(Lsh经销商表Repository lsh经销商表Repository) {
        ApprovalUtils.dealerRepo = lsh经销商表Repository;
    }

    @Autowired
    public void set用户Repository(com.iris.live.services.data.repositories.用户Repository 用户Repository) {
        ApprovalUtils.userRepo = 用户Repository;
    }

    @Autowired
    public void set报价单表Repository(com.iris.live.services.data.repositories.报价单表Repository 报价单表Repository) {
        ApprovalUtils.qutdSheetRepo = 报价单表Repository;
    }

    @Autowired
    public void setLsh车型Repository(Lsh车型Repository lsh车型Repository) {
        ApprovalUtils.carRep = lsh车型Repository;
    }

    @Autowired
    public void setLsh库存表Repository(Lsh库存表Repository lsh库存表Repository) {
        ApprovalUtils.lsh库存表Repository = lsh库存表Repository;
    }

    @Autowired
    public void setApprovalService(ApprovalService approvalService) {
        ApprovalUtils.approvalService = approvalService;
    }

    @Autowired
    public void setItask基础设置Repository(Itask基础设置Repository itask基础设置Repository) {
        ApprovalUtils.itskSetRepo = itask基础设置Repository;
    }
}
